package top.techqi.usbd

import android.hardware.usb.UsbDevice
import android.util.SparseArray
import top.techqi.usbd.finder.CdcAcmFinder
import top.techqi.usbd.finder.Wch341Finder

object UsbProber {
    private val finders = mutableListOf(Wch341Finder, CdcAcmFinder)

    operator fun plusAssign(finder: UsbFinder) {
        finders.add(finder)
    }

    fun detectDrivers(device: UsbDevice): SparseArray<Pair<String, Class<out UsbDriver>>> {
        val count = device.interfaceCount
        val remains = HashSet<Int>()
        for (index in 0..<count) {
            remains.add(device.getInterface(index).id)
        }

        val drivers = SparseArray<Pair<String, Class<out UsbDriver>>>()
        finders.forEach {
            if (remains.isEmpty()) return@forEach
            it.detectDrivers(device, remains, drivers)
        }
        return drivers
    }
}
